package com.smartmail.receiving;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.util.Log;

/**
 * Receiver which interrupts or resumes all AbstractRetrievalThreads for 
 * email accounts in the program, depending on the current state of Internet connection.
 * 
 * When Internet Connection is lost - all threads are stopped.
 * When Internet Connection is restored - all threads are resumed.
 * 
 * @author Tomek
 *
 */

public class ConnectivityBroadcastReceiver extends BroadcastReceiver{

	/**
	 * Constructor.
	 * 
	 * @param retrievalService - Android's Service object - RetrievalService.
	 */
	protected ConnectivityBroadcastReceiver(RetrievalService retrievalService){
		
		_retrievalService = retrievalService;
	}
	

	/**
	 * Invoked when Internet Connection status changed.
	 */
	@Override
	public void onReceive(Context context, Intent intent) {


		boolean isNetworkDown = intent.getBooleanExtra(
				ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
		if (isNetworkDown) {
			
			/**
			 * RetrievalService will stop all threads, each of them is listening
			 * on one particular mail box
			 */
			if(_retrievalService != null)
				_retrievalService.stopAllThreads();
			
			Log.d(_logTag,"ConnectivityBroadReceiver - Network Connection is down");
		} else {
			
			/**
			 * RetrievalService will resume all threads,
			 */
			if(_retrievalService != null)
				_retrievalService.resumeAllThreads();
			
			Log.d(_logTag,"ConnectivityBroadReceiver - Network Connection is up");
		}
		
	}
	
	/**
	 * log tag for logging purposes
	 */
	protected static String _logTag = "com.smartmail.receiving";
	
	/**
	 * instance of RetrievalService which owns instance of that 
	 * BroadcastReceiver
	 */
	private RetrievalService _retrievalService;
	

}